#!/bin/bash

function symlink_overwrite()
{
	[ "$2" ] || return 1
	[ -e "$2" ] &&
	{
		rm "$2" || return 1
	}
	ln -vsf "$1" "$2" || return 1
	return 0
}

function upper_symlink_base()
{
	local lowerdir upperdir

	lowerdir="$1/$3"
	upperdir="$2/$(echo $3 | tr [:lower:] [:upper:])"

	mkdir "${upperdir}" -pv || return 1

	ls "${lowerdir}" | while read line
	do
		if [ -d "${lowerdir}/${line}" ]
		then
			upper_symlink_base "${lowerdir}" "${upperdir}" "${line}" || return 1
		else
			symlink_overwrite "${lowerdir}/${line}" "${upperdir}/${line}" || return 1
		fi
	done

	return 0
}

function upper_symlink_main()
{
	local upperdir filename

	[ "$2" ] || return 1

	filename="$(basename $1)"

	if [ -d "$2" ]
	then
		upperdir="$2"
	else
		upperdir="$(dirname $1)"
		mkdir -pv "${upperdir}" || return 1
	fi

	if [ -d "$1" ]
	then
		upper_symlink_base "$(dirname $1)" "${upperdir}" "${filename}" || return 1
	else
		symlink_overwrite "$1" "${upperdir}/${filename}" || return 1
	fi

	return 0
}

upper_symlink_main "$1" "$2"
